package com.medical.admin.hospital.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.medical.admin.hospital.common.dto.ComboDto;
import com.medical.admin.hospital.common.vo.*;
import com.medical.admin.hospital.entity.*;
import com.medical.admin.hospital.mapper.*;
import com.medical.admin.hospital.service.ComboService;
import com.qf.medical.ex.BaseException;
import com.qf.medical.response.ResponseCode;
import com.qf.medical.utils.BeanConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ComboServiceImpl implements ComboService {
    @Resource
    private ComboMapper comboMapper;

    @Resource
    private ComboTypeMapper comboTypeMapper;

    @Resource
    private HospitalMapper hospitalMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private ComboProjectMapper comboProjectMapper;

    /**
     * 动态分页查询套餐信息
     * @param comboTypeName
     * @param comboName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageVo<ComboVo> list(String comboTypeName, String comboName, int pageNum, int pageSize) {
        if (comboTypeName!=null){
            ComboType comboType =comboTypeMapper.findByComboTypeName(comboTypeName);
            //通过套餐类型名称查询id
            List<ComboVo> comboVoList = comboMapper.pageList(comboType.getComboTypeId(),comboName,(pageNum-1)*pageSize,pageSize);
            PageVo<ComboVo> pageCombos = new PageVo<>();
            pageCombos.setRows(comboVoList);
            pageCombos.setTotal(comboVoList.size());
            return pageCombos;
        }
        List<ComboVo> comboVoList = comboMapper.pageList(null,comboName,(pageNum-1)*pageSize,pageSize);
        PageVo<ComboVo> pageCombos = new PageVo<>();
        pageCombos.setRows(comboVoList);
        pageCombos.setTotal(comboVoList.size());
        return pageCombos;
    }

    /**
     * 新增套餐信息
     * @param comboDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class,timeout = 5)
    public Integer insert(ComboDto comboDto) {
        //通过套餐名称判断套餐是否存在
        Combo combo = comboMapper.findByComboName(comboDto.getComboName());
        if (ObjectUtil.isNotEmpty(combo)){
            throw new BaseException(ResponseCode.COMBO_EXIT_ERROR);
        }

        //转换对象
        combo = BeanConvertUtils.convertTo(comboDto, Combo::new);

        //通过套餐类型名称查询id
        ComboType comboType =comboTypeMapper.findByComboTypeName(comboDto.getComboTypeName());
        combo.setComboTypeId(comboType.getComboTypeId());

        //通过医院名称查询id
        Hospital hospital=hospitalMapper.findByHospitalName(comboDto.getHospitalName());
        combo.setHospitalId(hospital.getHospitalId());

        //新增套餐信息
        int count = comboMapper.insert(combo);
        if (count!=1){
            throw new BaseException(ResponseCode.SYS_ERROR);
        }
        //通过项目名称获取id
        ArrayList<Long> ids = new ArrayList<>();
        List<String> projectNames = comboDto.getProjectNames();
        for (String projectName:projectNames) {
            Project project = projectMapper.findByProjectName(projectName);
            ids.add(project.getProjectId());
        }

        //新增套餐项目中间表信息,尽量不适用for循环批量增加，影响性能
        /*comboDto.getProjectNames().stream().map(projectName->{
            //通过项目名称获取项目id
            Project project = projectMapper.findByProjectName(projectName);
            ComboProject.builder().projectId(project.getProjectId()).comboId(combo.getComboId());
            comboProjectMapper.insert()
        });}*/

        return comboProjectMapper.insertComboProject(combo.getComboId(),ids);
    }


    /**
     * 修改套餐信息
     * @param comboDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class,timeout = 5)
    public Integer update(ComboDto comboDto) {
        //通过套餐名称判断套餐是否存在
        Combo combo = comboMapper.findByComboName(comboDto.getComboName());
        Optional.ofNullable(combo).orElseThrow(()->new BaseException(ResponseCode.COMBO_NOT_EXIT_ERROR));

        //转换对象
        Combo cb = BeanConvertUtils.convertTo(comboDto, Combo::new);

        //通过套餐类型名称查询id
        ComboType comboType =comboTypeMapper.findByComboTypeName(comboDto.getComboTypeName());
        cb.setComboTypeId(comboType.getComboTypeId());

        //通过医院类型名称查询id
        Hospital hospital=hospitalMapper.findByHospitalName(comboDto.getHospitalName());
        cb.setHospitalId(hospital.getHospitalId());

        cb.setComboId(combo.getComboId());
        //修改套餐信息
        int count = comboMapper.updateById(cb);
        if (count!=1){
            throw new BaseException(ResponseCode.SYS_ERROR);
        }

        //通过项目名称获取id
        ArrayList<Long> ids = new ArrayList<>();
        List<String> projectNames = comboDto.getProjectNames();
        for (String projectName:projectNames) {
            Project project = projectMapper.findByProjectName(projectName);
            ids.add(project.getProjectId());
        }

        //删除原先绑定的项目信息，再新增
        comboProjectMapper.deleteByComboId(cb.getComboId());

        return comboProjectMapper.insertComboProject(combo.getComboId(),ids);
    }

    /**
     * 删除套餐信息
     * @param comboId
     * @return
     */
    @Override
    public Integer delete(Long comboId) {
        Combo combo = comboMapper.selectById(comboId);
        //判断套餐是否存在
        Optional.ofNullable(combo).orElseThrow(()->new BaseException(ResponseCode.COMBO_NOT_EXIT_ERROR));
        //判断套餐是否已删除
        if (combo.getState()!=1){
            throw new BaseException(ResponseCode.COMBO_TYPE_NOT_EXIST_ERROR);
        }
        combo.setState(0);
        int count = comboMapper.updateById(combo);
        if (count!=1){
            throw new BaseException(ResponseCode.SYS_ERROR);
        }
        return count;
    }

    /**
     * 查询套餐信息详情
     * @param comboId
     * @return
     */
    @Override
    public ComboVo select(Long comboId) {
        Combo combo = comboMapper.selectById(comboId);
        Optional.ofNullable(combo).orElseThrow(()-> new BaseException(ResponseCode.COMBO_NOT_EXIT_ERROR));
        if (combo.getState()!=1){
            throw new BaseException(ResponseCode.COMBO_NOT_EXIT_ERROR);
        }
        return BeanConvertUtils.convertTo(combo,ComboVo::new);
    }

    /**
     * 获取下拉套餐类型信息
     * @return 注：如果下拉写成一个接口，异常不好处理。一个抛异常，全部都异常
     */
    @Override
    public DownMenu selectComboType() {
        //获取套餐类型信息
        List<ComboType> comboTypes = comboTypeMapper.selectList(new QueryWrapper<>());
        //判断套餐类型信息是否为空
        Optional.ofNullable(comboTypes).orElseThrow(()->new BaseException(ResponseCode.COMBO_TYPE_NOT_EXIST_ERROR));
        return DownMenu.builder().comboTypes(BeanConvertUtils.convertListTo(comboTypes, ComboTypeVo::new)).build();
    }

    /**
     * 获取下拉医院信息
     * @return
     */
    @Override
    public DownMenu selectHospital() {
        //获取医院信息
        List<Hospital> hospitalList = hospitalMapper.selectList(new QueryWrapper<>());
        //判断医院信息是否为空
        Optional.ofNullable(hospitalList).orElseThrow(()->new BaseException(ResponseCode.HOSPITAL_NOT_EXIST_ERROR));
        return DownMenu.builder().hospitals(BeanConvertUtils.convertListTo(hospitalList, HospitalVo::new)).build();
    }

    /**
     * 获取下拉项目信息
     * @return
     */
    @Override
    public DownMenu selectProject() {
        //获取项目信息
        List<Project> projects = projectMapper.selectList(new QueryWrapper<>());
        //判断项目信息是否为空
        Optional.ofNullable(projects).orElseThrow(()->new BaseException(ResponseCode.PROJECT_NOT_EXIT_ERROR));
        return DownMenu.builder().projects(BeanConvertUtils.convertListTo(projects, ProjectVo::new)).build();
    }
}
